package services

import (
	"longmen/server/config/global"
	"longmen/server/pkg/db/redis/cache"
	"time"

	"gorm.io/gorm"
	"longmen/server/pkg/common/api_models"
)

func (s *Service) Maintain(device int) (*api_models.MaintainResp, error) {
	var r = &api_models.MaintainResp{}
	cacheKey := "maintian"
	cache.GetCachedData(cacheKey, r)
	if r.Status > 0 {
		return r, nil
	}

	err := global.GetR().Table("db_maintain").
		Where("device=? and remind_time<=? and end_time>=? and status=1", device, time.Now().Unix(), time.Now().Unix()).
		Order("id desc, update_time desc").
		Limit(1).
		Find(&r).Error
	if err == gorm.ErrRecordNotFound {
		return nil, nil
	}
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	now := time.Now().Unix()
	if now >= r.RemindTime && now <= r.StartTime {
		r.Status = 1
	}

	if now >= r.RemindTime && now >= r.StartTime {
		r.Status = 2
	}

	if now > r.EndTime {
		r.Status = 3
	}
	cache.SetCacheData(cacheKey, r, time.Second*10)
	return r, nil
}
